<script>
import { getStoreOptions, getDataCycleOptions, page, downloadExcel } from "@/views/product/details/api"
import SelectColumn from "@/components/utils/SelectColumn.vue";
import { formatPercentage, isNull } from "@/utils/service";
import download from "@/plugins/download";

export default {
  name: "index",
  components: { SelectColumn },
  computed: {},
  created() {
    // 初始化 checkedColumns 且将 tableShow 对象的每个属性为布尔值且默认为 true
    const initialProperties =
      [
        "storeName", "dataCycle", "productName", "productId", "categoryName", "productVisitorNums", "productBrowseNums", "paymentNums",
        "paymentBuyerNums", "paymentOrderNums", "transactionAmount", "orderNumberOfPeople", "paymentConversionRate",
        "placeOrderRate", "payoutRate", "productCollectionNums", "numberOfGroupOrders", "productGroupNums",
        "uvValue", "customerUnitPrice", "collectionRate", "productHelpPlatformRate", "createTime", "updateTime"
      ];
    this.tableShow = Object.fromEntries(initialProperties.map(property => [property, true]));
    this.checkedColumns = initialProperties;
  },
  mounted() {
    this.getDetailsList()
  },
  data() {
    let _vm = this;
    return {
      storeNameOptions: {
        data: [],
        loading: true,
      },

      dataCycleOptions: {
        data: [],
        loading: true,
      },

      /** 搜索字段 */
      searchFiled: {
        storeName: "",
        dataCycle: "",
        productId: void 0,
      },

      table: {
        tbLoading: false,
        /* 选中行数据 */
        sRows: [],
        data: [],
        pageNo: 1,
        pages: 0,
        pageSize: 30,
        pageCount: 0,
        sortField: "",
        sortMode: void 0,
        handleSizeChange(pageSize) {
          if (pageSize === _vm.table.pageSize) {
            return;
          }
          _vm.table.pageSize = pageSize;
          _vm.getDetailsList();
        },
        handleCurrentChange(pageNo) {
          if (pageNo === _vm.table.pageNo) {
            return;
          }
          _vm.table.pageNo = pageNo;
          _vm.getDetailsList();
        },
        sRowChange(rows) {
          _vm.table.sRows = rows;
        }
      },
      tableShow: {},
      checkedColumns: [],
    }
  },
  methods: {
    isNull,
    tableDataProvider(){
      return JSON.parse(JSON.stringify(this.table.data))
    },
    toRender(componentData) {
      this.table.data = componentData.tableList;
    },
    getStoreOptions() {
      this.storeNameOptions.loading = true;
      getStoreOptions().then((res) => {
        this.storeNameOptions.data = res;
      }).finally(() => {
        this.storeNameOptions.loading = false;
      });
    },
    getDataCycleOptions() {
      this.dataCycleOptions.loading = true;
      getDataCycleOptions().then((res) => {
        this.dataCycleOptions.data = res;
      }).finally(() => {
        this.dataCycleOptions.loading = false;
      });
    },
    getDetailsList() {
      let _t = this;
      _t.table.tbLoading = true;
      let params = {
        pageNo: _t.table.pageNo,
        pageSize: _t.table.pageSize,
        storeName: _t.searchFiled.storeName,
        dataCycle: _t.searchFiled.dataCycle,
        productId: _t.searchFiled.productId,
        sortField: _t.table.sortField,
        sortMode: _t.table.sortMode
      }
      page(params).then((res) => {
        _t.table.data = res.list
        _t.table.pageNo = res.pageNo
        _t.table.pageCount = res.total
        _t.table.pageSize = res.pageSize
        _t.table.pages = res.pages
      }).finally(() => {
        _t.table.tbLoading = false;
      })
    },
    download() {
      if(isNull(this.searchFiled.storeName)) {
        this.$message.warning('请选择店铺名称')
        return
      }
      let param = {
        productId: this.searchFiled.productId,
        storeName: this.searchFiled.storeName,
        dataCycle: this.searchFiled.dataCycle
      };

      const fileName = this.searchFiled.storeName;

      downloadExcel(this, param, res => {
        download.excel(res.data, fileName)
        this.$message.success('下载成功')
      })
    },
    /* 清空分页条件 */
    clearableSearchInput(){
      this.searchFiled.storeName = ""
      this.searchFiled.dataCycle = ""
      this.searchFiled.productId = void 0
      this.getDetailsList()
    },
    tableSortChange(column, prop, order){
      if (!isNull(column.order)) {
        this.table.sortField = column.prop;
        if (column.order.startsWith("asc")) {
          this.table.sortMode = "ASC";
        } else {
          this.table.sortMode = "DESC";
        }
      } else {
        this.table.sortMode = "ASC";
      }
      this.getDetailsList()
    },
    formatDateToDay(dateString) {
      const date = new Date(dateString.dataDate);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');

      return `${year}-${month}-${day}`;
    },
    /** 表格值保留两位小数且空值将以 '-' 字符替代*/
    percentageWithFixedDigits2(row, column, cellValue, index) {
      if(typeof(cellValue) === 'number'){
        return cellValue.toFixed(2);
      }else if (typeof(cellValue) === 'string'){
        return cellValue ? cellValue : '-'
      }else {
        return '-'
      }
    },
    /** 将表格值转为百分比*/
    valueToPercentage(row, column, cellValue, index) {
      return formatPercentage(cellValue);
    },
    valueToCharacter(row, column, cellValue, index){
      return cellValue !== '' || cellValue !== undefined ? cellValue : '-'
    }
  }
};
</script>
<template>
  <div style="margin: 10px 0">
    <div class="header">
      <el-select
        @focus="getStoreOptions"
        style="width: 230px"
        size="mini"
        v-model="searchFiled.storeName" clearable filterable placeholder="请选择店铺名称">
        <el-option
          v-for="item in storeNameOptions.data"
          :key="item"
          :label="item"
          :value="item">
        </el-option>
      </el-select>

      <el-select
        clearable
        @focus="getDataCycleOptions"
        style="margin-left: 5px"
        size="mini"
        v-model="searchFiled.dataCycle"
        placeholder="请选择数据周期"
        :loading="dataCycleOptions.loading"
      >
        <el-option
          v-for="item in dataCycleOptions.data"
          :key="item"
          :label="item"
          :value="item">
        </el-option>
      </el-select>

      <el-input type="number" size="mini" class="searchInput" v-model="searchFiled.productId"
                placeholder="商品编号(精确)" :clearable=true />
      <el-button size="mini" type="primary" icon="el-icon-search" @click="getDetailsList()">搜索</el-button>
      <el-button size="mini" type="info" icon="el-icon-refresh" @click="clearableSearchInput()">清空</el-button>


      <template>
        <el-popconfirm
          confirm-button-text='好的'
          cancel-button-text='不用了'
          icon="el-icon-info"
          title="确定导出 Excel 表格文件吗？"
          @confirm="download"
        >
          <el-button slot="reference" style="margin-left: 10px" size="mini" type="success" icon="el-icon-download">导出</el-button>
        </el-popconfirm>
      </template>

<!--      <div style="margin-top: 10px">-->
<!--        <select-column-->
<!--          :tb-ref-name="'myTb'"-->
<!--          :tableShow="tableShow"-->
<!--          :defaultActivateColumns="checkedColumns"-->
<!--          :tableDataProvider="tableDataProvider"-->
<!--          @toRender="toRender"-->
<!--        >-->
<!--        </select-column>-->
<!--      </div>-->

    </div>

    <div class="main">
      <el-table
        ref="myTb"
        @selection-change="table.sRowChange"
        v-loading="table.tbLoading"
        element-loading-text="拼命加载中"
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(0, 0, 0, 0.8)"
        style="width: 100%"
        height="77vh"
        :row-style="{height:'20px'}"
        :cell-style="{padding:'0px'}"
        border
        :data="table.data"
        @sort-change="tableSortChange"
      >
        <el-table-column fixed="left" :show-overflow-tooltip=true prop="storeName" label="店铺名称" align="center" width="200"
                         :formatter="valueToCharacter"/>
        <el-table-column prop="dataCycle" v-if="tableShow.dataCycle" label="数据周期" align="center" width="200"/>
        <el-table-column prop="productName" v-if="tableShow.productName" label="商品名称" align="center" width="300"
                         show-overflow-tooltip header-align="center" :formatter="valueToCharacter"/>
        <el-table-column prop="productId" v-if="tableShow.productId" label="商品ID" align="center" width="150"
                         :formatter="valueToCharacter"/>
        <el-table-column prop="categoryName" v-if="tableShow.categoryName" label="类目名称" align="center" width="150"
                         show-overflow-tooltip header-align="center" :formatter="valueToCharacter" />
        <el-table-column prop="productVisitorNums" v-if="tableShow.productVisitorNums" sortable label="商品访客数" align="center" width="120"
                         :formatter="valueToCharacter"/>
        <el-table-column prop="productBrowseNums" v-if="tableShow.productBrowseNums" sortable label="商品浏览量" align="center" width="120"
                         :formatter="valueToCharacter"/>
        <el-table-column prop="paymentNums" v-if="tableShow.paymentNums" sortable label="支付件数" align="center" width="120"
                         :formatter="valueToCharacter"/>
        <el-table-column prop="paymentBuyerNums" v-if="tableShow.paymentBuyerNums" sortable label="支付买家数" align="center" width="120"
                         :formatter="valueToCharacter"/>
        <el-table-column prop="paymentOrderNums" v-if="tableShow.paymentOrderNums" sortable label="支付订单数" align="center" width="120"
                         :formatter="valueToCharacter"/>
        <el-table-column prop="transactionAmount" v-if="tableShow.transactionAmount" sortable label="交易金额" align="center" width="120"
                         :formatter="percentageWithFixedDigits2"/>
        <el-table-column prop="orderNumberOfPeople" v-if="tableShow.orderNumberOfPeople" sortable label="下单人数" align="center" width="120"
                         :formatter="valueToCharacter"/>
        <el-table-column prop="paymentConversionRate" v-if="tableShow.paymentConversionRate" sortable label="支付转化率" align="center" width="120">
          <template #default="{row, column, $index}">
            {{ !isNull(row.paymentConversionRate) ? row.paymentConversionRate + '%' : '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="placeOrderRate" v-if="tableShow.placeOrderRate" sortable label="下单率" align="center" width="120">
          <template #default="{row, column, $index}">
            {{ !isNull(row.placeOrderRate) ? row.placeOrderRate + '%' : '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="payoutRate" v-if="tableShow.payoutRate" sortable label="支付率" align="center" width="120">
          <template #default="{row, column, $index}">
            {{ !isNull(row.payoutRate) ? row.payoutRate + '%' : '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="productCollectionNums" v-if="tableShow.productCollectionNums" sortable label="商品收藏用户数" align="center" width="150"
                         :formatter="valueToCharacter"/>
        <el-table-column prop="numberOfGroupOrders" v-if="tableShow.numberOfGroupOrders" sortable label="成团订单数" align="center" width="120"
                         :formatter="valueToCharacter"/>
        <el-table-column prop="productGroupNums" v-if="tableShow.productGroupNums" sortable label="商品成团件数" align="center" width="130"
                         :formatter="valueToCharacter"/>
        <el-table-column prop="uvValue" v-if="tableShow.uvValue" sortable label="UV价值" align="center" width="120"
                         :formatter="percentageWithFixedDigits2"/>
        <el-table-column prop="customerUnitPrice" v-if="tableShow.customerUnitPrice" sortable label="客单价" align="center" width="120"
                         :formatter="percentageWithFixedDigits2"/>
        <el-table-column prop="collectionRate" v-if="tableShow.collectionRate" sortable label="收藏率" align="center" width="120">
          <template #default="{row, column, $index}">
            {{ !isNull(row.collectionRate) ? row.collectionRate + '%' : '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="productHelpPlatformRate" v-if="tableShow.productHelpPlatformRate" sortable label="商品求助平台率" align="center" width="150">
          <template #default="{row, column, $index}">
            {{ !isNull(row.productHelpPlatformRate) ? row.productHelpPlatformRate + '%' : '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="createTime" v-if="tableShow.createTime" sortable label="创建时间" align="center" width="180"/>
        <el-table-column prop="updateTime" v-if="tableShow.updateTime" sortable label="修改时间" align="center" width="180"/>
      </el-table>
    </div>

    <div class="footer">
      <div>
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          @size-change=table.handleSizeChange
          @current-change=table.handleCurrentChange
          :total=table.pageCount
          :page-sizes="[30, 50, 100, 300]"
          :page-size=table.pageSize
          :page-count=table.pages
          :current-page=table.pageNo
        >
        </el-pagination>
      </div>
    </div>
  </div>
</template>
<style scoped>
.header {
  margin: 10px 0 10px 0
}

.searchInput {
  margin: 0 5px;
  width: 13%;
}

.main{
  margin: 10px 0 10px 0
}

.footer{
  display: flex;
  justify-content: space-between;
}
</style>